<template>
  <view class="ts-column ts-flex-item">
    <!-- <ts-banner @tap="openStore" image="http://via.placeholder.com/750x375"></ts-banner> -->

    <view class="ts-flex ts-column ts-flex-item">
      <view class="segmented-head">
        <ts-segmented-control :values="tabs" v-on:clickItem="onClickItem" style-type="text" active-color="#d81e06"
          borderColor="#d81e06"></ts-segmented-control>
      </view>
      <view class="segmented-content">
        <view v-show="currentTab === 0">
          <view class="ts-flex ts-column ts-flex-item">
            <view class="ts-list">
              <view class="ts-list-cell" hover-class="ts-list-cell-hover" v-for="(item, index2) in tabListDataShopProduct.data"
                :key="index2">
                <view class="ts-media-list">
                  <image class="ts-media-list-logo" :src="item.img" @tap="showDetail(item)"></image>
                  <view class="ts-media-list-body">
                    <view class="ts-media-list-text-top ts-ellipsis-2" @tap="showDetail(item)">
                      {{ item.title }}
                    </view>
                    <view class="ts-media-list-text-middle">
                      <view class="ts-flex ts-flex-item ts-flex-row" style="justify-content: space-between; align-items: center;">
                        <text class="ts-h6">{{ item.seller_count }}</text>
                        <text class="ts-h6">库存剩{{ item.stock }}件</text>
                      </view>
                    </view>
                    <view class="ts-media-list-text-bottom">
                      <view class="ts-flex ts-flex-item ts-flex-row" style="justify-content: space-between; align-items: center;">
                        <view class="ts-flex ts-flex-item">
                          <text class="ts-h4 ts-text-bold">￥{{ item.price / 100 }}</text>
                          <text class="ts-h4 ts-text-red ts-text-discount" style="padding-left: 10px;">
                            ￥{{ item.origin_price / 100 }}
                          </text>
                        </view>
                        <view class="ts-flex">
                          <!-- #ifdef APP-PLUS -->
                          <view class="button-row">
                            <button class="mini-btn" type="warn" size="mini" @tap="showDetail(item)">
                              购买
                            </button>
                            <button class="mini-btn" type="default" size="mini" :data-value="item" @tap="share">
                              分享
                            </button>
                          </view>
                          <!-- #endif -->
                          <!-- #ifdef MP-WEIXIN -->
                          <view>
                            <button class="mini-btn" size="mini" type="default" open-type="share" :data-value="item">
                              分享
                            </button>
                          </view>
                          <!-- #endif -->
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="loadMore" @tap="loadMoreShopProduct">
              {{ tabListDataShopProduct.loadMoreText }}
            </view>
          </view>
        </view>
        <view v-show="currentTab === 1">
          <view class="ts-flex ts-column ts-flex-item">
            <view class="ts-list">
              <view class="ts-list-cell" hover-class="ts-list-cell-hover" v-for="(item, index2) in tabListDataTemaiProduct.data"
                :key="index2">
                <view class="ts-media-list">
                  <image class="ts-media-list-logo" :src="item.img" @tap="showDetail(item)"></image>
                  <view class="ts-media-list-body">
                    <view class="ts-media-list-text-top ts-ellipsis-2" @tap="showDetail(item)">
                      {{ item.title }}
                    </view>
                    <view class="ts-media-list-text-middle">
                      <view class="ts-flex ts-flex-item ts-flex-row" style="justify-content: space-between; align-items: center;">
                        <text class="ts-h6">{{ item.seller_count }}</text>
                        <text class="ts-h6">库存剩{{ item.stock }}件</text>
                      </view>
                    </view>
                    <view class="ts-media-list-text-bottom">
                      <view class="ts-flex ts-flex-item ts-flex-row" style="justify-content: space-between; align-items: center;">
                        <view class="ts-flex ts-flex-item">
                          <text class="ts-h4 ts-text-bold">￥{{ item.price / 100 }}</text>
                          <text class="ts-h4 ts-text-red ts-text-discount" style="padding-left: 10px;">
                            ￥{{ item.origin_price / 100 }}
                          </text>
                        </view>
                        <view class="ts-flex">
                          <!-- #ifdef APP-PLUS -->
                          <view class="button-row">
                            <button class="mini-btn" type="warn" size="mini" @tap="showDetail(item)">
                              购买
                            </button>
                            <button class="mini-btn" type="default" size="mini" :data-value="item" @tap="share">
                              分享
                            </button>
                          </view>
                          <!-- #endif -->
                          <!-- #ifdef MP-WEIXIN -->
                          <view>
                            <button class="mini-btn" size="mini" type="default" open-type="share" :data-value="item">
                              分享
                            </button>
                          </view>
                          <!-- #endif -->
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="loadMore" @tap="loadMoreTemaiProduct">
              {{ tabListDataTemaiProduct.loadMoreText }}
            </view>
          </view>
        </view>
        <view v-show="currentTab === 2">
          <view class="ts-flex ts-column ts-flex-item">
            <ts-search-bar v-model="keywords" placeholder="检索全部商品" @search="search"></ts-search-bar>

            <view class="ts-list">
              <view class="ts-list-cell" hover-class="ts-list-cell-hover" v-for="(item, index2) in tabListDataSearchResult.data"
                :key="index2">
                <view class="ts-media-list">
                  <image class="ts-media-list-logo" :src="item.img" @tap="showDetail(item)"></image>
                  <view class="ts-media-list-body">
                    <view class="ts-media-list-text-top ts-ellipsis-2" @tap="showDetail(item)">
                      {{ item.title }}
                    </view>
                    <view class="ts-media-list-text-middle">
                      <view class="ts-flex ts-flex-item ts-flex-row" style="justify-content: space-between; align-items: center;">
                        <text class="ts-h6">{{ item.seller_count }}</text>
                        <text class="ts-h6">库存剩{{ item.stock }}件</text>
                      </view>
                    </view>
                    <view class="ts-media-list-text-bottom">
                      <view class="ts-flex ts-flex-item ts-flex-row" style="justify-content: space-between; align-items: center;">
                        <view class="ts-flex ts-flex-item">
                          <text class="ts-h4 ts-text-bold">￥{{ item.price / 100 }}</text>
                          <text class="ts-h4 ts-text-red ts-text-discount" style="padding-left: 10px;">
                            ￥{{ item.origin_price / 100 }}
                          </text>
                        </view>
                        <view class="ts-flex">
                          <!-- #ifdef APP-PLUS -->
                          <view class="button-row">
                            <button class="mini-btn" type="warn" size="mini" @tap="showDetail(item)">
                              购买
                            </button>
                            <button class="mini-btn" type="default" size="mini" :data-value="item" @tap="share">
                              分享
                            </button>
                          </view>
                          <!-- #endif -->
                          <!-- #ifdef MP-WEIXIN -->
                          <view>
                            <button class="mini-btn" size="mini" type="default" open-type="share" :data-value="item">
                              分享
                            </button>
                          </view>
                          <!-- #endif -->
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="loadMore" v-show="tabListDataSearchResult.showLoadMoreText" @tap="loadMoreSearchResult">
              {{ tabListDataSearchResult.loadMoreText }}
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>
<script>
  import tsBanner from 'components/teaset/components/ts-banner/ts-banner.vue';
  import tsSearchBar from 'components/teaset/components/ts-search-bar/ts-search-bar.vue';
  import tsSegmentedControl from 'components/teaset/components/ts-segmented-control/ts-segmented-control.vue';
  //导入业务数据获取服务
  import service from 'services/jingxuan-bedian.js';
  var self;
  export default {
    components: {
      tsBanner,
      tsSearchBar,
      tsSegmentedControl
    },
    data() {
      return {
        shopId: '682731', //贝店序号
        providerList: [],
        keywords: '水果',
        currentTab: 0,
        tabs: ['店长推荐', '今日特价', '产品搜索'],
        tabListDataShopProduct: {},
        tabListDataTemaiProduct: {},
        tabListDataSearchResult: {}
      };
    },
    computed: {},
    onUnload: function() {},
    onReachBottom: function() {
      // console.log('onReachBottom');
      if (this.currentTab == 0) {
        this.loadMoreShopProduct();
      } else if (this.currentTab == 1) {
        this.loadMoreTemaiProduct();
      } else if (this.currentTab == 2) {
        this.loadMoreSearchResult();
      }
    },
    // #ifdef MP-WEIXIN
    //分享按钮函数
    onShareAppMessage: function(options) {
      if (options.from === 'button') {
        // 来自页面内转发按钮
        let value = options.target.dataset.value;
        let iid = value.iid;
        let api = `https://m.beidian.com/detail/detail.html?iid=${iid}&shop_id=${this.shopId}`;
        return {
          title: value.title,
          // desc: value.desc,
          path: api,
          imageUrl: value.img
        };
      } else {
        return {
          title: '贺兰姑娘的贝店',
          // desc: '最具人气的小程序开发联盟!',
          path: `https://m.beidian.com/shop/shopkeeper.html?shop_id=${this.shopId}`,
          imageUrl: 'http://via.placeholder.com/750x375',
          success: function(res) {
            // 转发成功
            console.log('转发成功:' + JSON.stringify(res));
          },
          fail: function(res) {
            // 转发失败
            console.log('转发失败:' + JSON.stringify(res));
          }
        };
      }
    },
    // #endif
    methods: {
      onClickItem(index) {
        if (this.currentTab !== index) {
          this.currentTab = index;
        }
      },
      loadMoreShopProduct: async function() {
        let item = this.tabListDataShopProduct;
        // console.log('item:' + JSON.stringify(item));
        if (item.isLoading) return;
        if (item.hasMore) {
          item.isLoading = true; //阻止重复提交请求
          //等待请求下一页数据
          await service.getShopProducts(self.shopId, item.page + 1).then(data => {
            if (data) {
              item.data = item.data.concat(data);
              item.page = item.page + 1; //修改数据分页编号
            } else {
              item.hasMore = false;
            }
            if (!item.hasMore) {
              item.loadMoreText = '没有更多数据了!';
            }
            item.isLoading = false;
          });
        }
      },
      loadMoreTemaiProduct: async function() {
        let item = this.tabListDataTemaiProduct;
        // console.log('item:' + JSON.stringify(item));
        if (item.isLoading) return;
        if (item.hasMore) {
          item.isLoading = true; //阻止重复提交请求
          //等待请求下一页数据
          await service.getTemaiProducts(self.shopId, item.page + 1).then(data => {
            if (data) {
              item.data = item.data.concat(data);
              item.page = item.page + 1; //修改数据分页编号
            } else {
              item.hasMore = false;
            }
            if (!item.hasMore) {
              item.loadMoreText = '没有更多数据了!';
            }
            item.isLoading = false;
          });
        }
      },
      loadMoreSearchResult: async function() {
        let item = this.tabListDataSearchResult;
        // console.log('item:' + JSON.stringify(item));
        if (item.isLoading) return;
        if (item.hasMore) {
          item.isLoading = true; //阻止重复提交请求
          //等待请求下一页数据
          // let keywords = '笔记本';
          await service.search(this.keywords, item.page + 1).then(data => {
            if (data) {
              item.data = item.data.concat(data);
              item.page = item.page + 1; //修改数据分页编号
            } else {
              item.hasMore = false;
            }
            if (!item.hasMore) {
              item.loadMoreText = '没有更多数据了!';
            }
            item.isLoading = false;
          });
        }
      },
      search(keywords) {
        console.log(keywords);
        console.log('Keywords:' + this.keywords);
        this.tabListDataSearchResult = {
          data: [],
          page: 0,
          hasMore: true,
          isLoading: false,
          loadMoreText: '点击加载更多...',
          showLoadMoreText: true
        };
        this.loadMoreSearchResult();
      },
      openStore() {
        // #ifdef APP-PLUS
        //https://m.beidian.com/shop/shopkeeper.html?shop_id=682731
        let api = `https://m.beidian.com/shop/shopkeeper.html?shop_id=${this.shopId}`;
        plus.runtime.openURL(api);
        // #endif
      },
      showDetail(item) {
        //https://m.beidian.com/detail/detail.html?iid=29064225&shop_id=682731
        let iid = item.iid;
        let api = `https://m.beidian.com/detail/detail.html?iid=${iid}&shop_id=${this.shopId}`;
        // 贝店程序限制，WebView模式下无法打开详情页，调用外部浏览器打开
        // #ifdef APP-PLUS
        plus.runtime.openURL(api);
        // #endif
        // 微信小程序中暂时没有解决方案
        // #ifdef MP-WEIXIN
        uni.setClipboardData({
          data: api,
          success: function() {
            uni.showModal({
              title: '提示',
              content: '链接已复制，请黏贴到浏览器中访问',
              showCancel: false,
              success: function(res) {
                if (res.confirm) {
                  console.log('用户点击确定');
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              }
            });
          }
        });
        // #endif
      },
      // #ifdef APP-PLUS
      share(e) {
        const item = e.target.dataset['value'];
        console.log(JSON.stringify(item));
        // console.log(JSON.stringify(e));
        let iid = item.iid;
        let api = `https://m.beidian.com/detail/detail.html?iid=${iid}&shop_id=${this.shopId}`;
        if (this.providerList.length === 0) {
          uni.showModal({
            title: '当前环境无分享渠道!',
            showCancel: false
          });
          return;
        }
        let itemList = this.providerList.map(function(value) {
          return value.name;
        });
        uni.showActionSheet({
          itemList: itemList,
          success: res => {
            uni.share({
              provider: this.providerList[res.tapIndex].id,
              scene: this.providerList[res.tapIndex].type &&
                this.providerList[res.tapIndex].type === 'WXSenceTimeline' ?
                'WXSenceTimeline' : 'WXSceneSession',
              type: 0,
              title: item.title,
              summary: item.desc,
              imageUrl: item.img,
              href: api,
              success: res => {
                console.log('success:' + JSON.stringify(res));
              },
              fail: e => {
                uni.showModal({
                  content: e.errMsg,
                  showCancel: false
                });
              }
            });
          }
        });
      }
      // #endif
    },
    onLoad: async function(e) {
      self = this;
      this.shopId = e.shop_id | this.shopId;
      //初始化segment-control的数据信息，每个segment单独管理
      this.tabListDataSearchResult = {
        data: [],
        page: 0,
        hasMore: true,
        isLoading: false, //阻止重复加载数据
        loadMoreText: '点击加载更多...',
        showLoadMoreText: false
      };
      this.tabListDataShopProduct = {
        data: [],
        page: 0,
        hasMore: true,
        isLoading: false,
        loadMoreText: '点击加载更多...'
      };
      this.tabListDataTemaiProduct = {
        data: [],
        page: 0,
        hasMore: true,
        isLoading: false,
        loadMoreText: '点击加载更多...'
      };
      await self.loadMoreShopProduct();
      await self.loadMoreTemaiProduct();
      uni.getProvider({
        service: 'share',
        success: e => {
          let data = [];
          // console.log(JSON.stringify(e.provider))
          for (let i = 0; i < e.provider.length; i++) {
            //["sinaweibo","tencentweibo","qq","weixin"]
            switch (e.provider[i]) {
              case 'weixin':
                data.push({
                  name: '分享到微信好友',
                  id: 'weixin'
                });
                data.push({
                  name: '分享到微信朋友圈',
                  id: 'weixin',
                  type: 'WXSenceTimeline'
                });
                break;
              case 'qq':
                data.push({
                  name: '分享到QQ',
                  id: 'qq'
                });
                break;
              case 'sinaweibo':
                data.push({
                  name: '新浪微博',
                  id: 'sinaweibo'
                });
                break;
              default:
                break;
            }
          }
          self.providerList = data;
        },
        fail: e => {
          console.log('获取登录通道失败' + JSON.stringify(e));
        }
      });
    }
  };
</script>

<style lang="scss">
  /* page,
view {
  display: flex;
  flex-direction: row;
}

page {
  min-height: 100%;
  font-size: 32upx;
  line-height: 1.6;
} */

  .loadMore {
    width: 750upx;
    text-align: center;
    justify-content: center;
    align-items: center;
    line-height: 100upx;
    font-size: 30upx;
  }

  .segmented-head {
    line-height: 100upx;
    height: 100upx;
    align-items: center;
    justify-content: center;
    flex-direction: row;
    display: flex;
    width: 100%;
    text-align: center;
  }

  .segmented-content {
    display: flex;
    flex-direction: column;
    align-content: flex-start;
    justify-content: flex-start;
  }

  .padding {
    padding: 20upx;
  }

  .ts-list:before {
    position: absolute;
    z-index: 10;
    right: 0;
    top: 0;
    left: 0;
    height: 0upx;
    content: '';
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
    background-color: #c8c7cc;
  }

  .ts-media-list-logo {
    height: 180upx;
    width: 180upx;
    margin-right: 10upx;
  }

  .ts-media-list-body {
    height: 200upx;
    display: flex;
    flex: 1;
    flex-direction: column;
  }

  .ts-media-list-text-top {
    font-size: 25upx;
    line-height: 30upx;
    height: 60upx;
  }

  .ts-media-list-text-middle {
    font-size: 20upx;
    width: 100%;
  }

  .ts-media-list-text-bottom {
    font-size: 20px;
    color: #8f8f94;
    width: 100%;
  }

  .button-row {}

  .button-row button {
    margin-left: 10upx;
  }
</style>
